package org.example.service.handler;

import com.example.user.UserInformation;
import com.example.user.UserInformationRequest;
import io.grpc.stub.StreamObserver;
import org.example.exceptions.UnknownUserException;
import org.example.repository.PortfolioItemRepository;
import org.example.repository.UserRepository;
import org.example.util.EntityMessageMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 负责处理用户信息并返回相应
 * @author Administrator
 */
@Service
public class UserInfomationRequestHandler {
    private final UserRepository userRepository;
    private final PortfolioItemRepository portfolioItemRepository;

    public UserInfomationRequestHandler(UserRepository userRepository, PortfolioItemRepository portfolioItemRepository) {
        this.userRepository = userRepository;
        this.portfolioItemRepository = portfolioItemRepository;
    }

    public UserInformation getUserInformation(UserInformationRequest request) {
        var user = this.userRepository.findById(request.getUserId())
                //用户不存在抛出自定义异常
                .orElseThrow(() -> {
                    return new UnknownUserException(request.getUserId());
                });
        //返回用户持有的股票数据集合  投资
        var allByUserId = this.portfolioItemRepository.findAllByUserId(request.getUserId());
        return EntityMessageMapper.toUserInformation(user, allByUserId);

    }
}
